package com.tp;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ParseException;
import android.widget.EditText;
import android.widget.Toast;

public class GetRes implements OnClickListener {

	Context activity;
	EditText obj;
	String types[];
	static JSONArray jArr;

	public GetRes(Activity activity, EditText v) {
		this.activity = activity;
		a(activity);
		obj = v;
	}

	public void a(Context cxt) {
		AlertDialog.Builder b = new AlertDialog.Builder(cxt);
		b.setTitle("Choose Restaurant");

		/*
		 * b.setItems(types, new OnClickListener() {
		 * 
		 * 
		 * 
		 * 
		 * 
		 * });
		 */
		// activity = cxt;
		ArrayList<String> arr = getRes();
		arr.add("Add New Restaurant");
		types = new String[arr.size()];
		types = arr.toArray(types);
		b.setItems(types, this);

		b.show();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.content.DialogInterface.OnClickListener#onClick(android.content
	 * .DialogInterface, int)
	 */
	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		/*
		 * switch (which) { case 0:
		 * 
		 * break; case 1: }
		 */
		if (types[which].equals("Add New Restaurant")) {
			activity.startActivity(new Intent(((Dialog) dialog).getContext(),
					Add.class));

		} else
			obj.setText(types[which]);
	}

	public ArrayList<String> getRes() {
		// END Convert response to string
		JSONArray jArray;
		JSONObject json_data = null;
		int i;
		ArrayList<String> r = new ArrayList<String>();
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/getAllRes", postParameters);

			jArray = new JSONArray(result);
			jArr = jArray;
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				// Log.d("A", json_data.getString("name"));
				r.add(json_data.getString("name"));
			}
			// return r;
		} catch (JSONException e1) {
			Toast.makeText(((ContextWrapper) activity).getBaseContext(),
					e1.toString(), Toast.LENGTH_SHORT).show();
		} catch (ParseException e1) {
			Toast.makeText(((ContextWrapper) activity).getBaseContext(),
					e1.toString(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return r;

	}
}
